const fs = require('fs');
var iconv = require('iconv-lite');
var cheerio = require('cheerio');
const { captureRejectionSymbol } = require('events');
module.exports = {
	tabsdata: [],
	// 去掉后缀名
	getFileName(data) {
		return data.substring(0, data.indexOf("."));
	},
	// 美化文本输出
	getContent(node) {
		let _this = module.exports;
		var a = node.contents();
		if (a.length == 0) {
			if (node.is('br')) {
				RST += '\n';
			} else {
				RST += node.text().trim();;
			}
		} else {
			node.contents().each(function (i, elem) {
				_this.getContent($(this));
			});

			if (node.is('p') || node.is('tr')) {
				RST += '\n';
			}
		}
	},
	//创建目录，如果已有则不创建
	mkDir(folderName) {
		return new Promise((resolve, reject) => {
			fs.readdir('./', (err, files) => {
				if (~files.indexOf(folderName)) {
					resolve(folderName);
				} else {
					fs.mkdir(`./${folderName}`, function (err) {
						err && reject(err);
						resolve(folderName);
					});
				}
			});
		});
	},
	//复制文件
	copyFile(targetFiledir, output) {
		let buf = fs.readFileSync(targetFiledir);
		fs.writeFile(output, buf, function (error) {
			if (error) {
				console.log(error);
				throw error;
			} else {
				console.log('文件已保存');
			}
		});
	},
	// 删除文件
	deleteall(path) {
		var files = [];
		let _this = module.exports;
		if (fs.existsSync(path)) {
			files = fs.readdirSync(path);
			files.forEach(function (file, index) {
				var curPath = path + "/" + file;
				if (fs.statSync(curPath).isDirectory()) { // recurse
					_this.deleteall(curPath);
				} else { // delete file
					fs.unlinkSync(curPath);
				}
			});
			fs.rmdirSync(path);
		}
	},
	// 所在目录进行遍历
	readDirSync(filePath) {
		var pa = fs.readdirSync(filePath);
		let _this = module.exports;
		pa.forEach(function (ele, index) {
			var info = fs.statSync(filePath + "/" + ele)
			if (info.isDirectory()) {
				// 如果是空文件夹 则执行删除操作
				if (_this.isEmptyDir(filePath + "/" + ele)) {
					console.log('delete foder=> ' + ele);
					fs.rmdirSync(filePath + "/" + ele);
				}
			} else {
				// console.log('不是空文件夹不执行删除操作===>');
			}
		})
	},
	// 判断是否是空文件夹
	isEmptyDir(fPath) {
		var pa = fs.readdirSync(fPath);
		if (pa.length === 0) {
			return true;
		} else {
			return false;
		}

	},
	checkdir(dirname) {
		if (dirname.includes('ios'))
			return '00_iOS'
		if (dirname.includes('android'))
			return '01_Android'
		if (dirname.includes('windows'))
			return '02_Windows'
		if (dirname.includes('c++'))
			return '03_C++'
		if (dirname.includes('macOS'))
			return '04_Windows'
	},
	//提取一个目录文件夹里指定类型（如：同一后缀名）的文件   先判断index中的内容
	extractFiles(folderTarget, format, title) {
		let path = require('path');//path模块
		let folderNew = `${folderTarget}_${format}`;
		console.log(folderNew)
		let _this = module.exports;
		const ergodicDir = (Path, folderNameNew, format) => {
			fs.readdir(Path, (err, files) => {
				err && console.warn('路径读取出错', err);
				//遍历读取到的文件列表
				files.forEach((filename, i) => {
					let filedir = path.join(Path, filename);//完整的路径
					//根据文件路径获取文件信息，返回一个fs.Stats对象
					fs.stat(filedir, (error, stats) => {
						error && console.warn('获取文件stats失败', error);
						let isFile = stats.isFile(); //是文件
						let isDir = stats.isDirectory(); //是文件夹
						// console.log(isFile, isDir)
						if (isFile) {
							if (filename.includes('index')) {
								console.log('index =>')
								var content = fs.readFileSync(filedir, 'utf-8');
								var $ = cheerio.load(content);
								let html = $('.contents').html()
								let html2 = $('.textblock').find('ul')
								let docs_tabs = [
									'<div class="docs-tabs">',
									'<div class="btn-group" role="group" aria-label="...">',
									'<a href="index.html" type="button" class="btn btn-default active">概览</a>'
								]
								_this.tabsdata = []
								$(html2).find('li').each(function (i, elem) {
									let href = $(elem).find('a').attr('href')
									let text = $(elem).find('a').text()
									_this.tabsdata.push({ href, text })
									docs_tabs.push(`<a href="${href}" type="button" class="btn btn-default">${text}</a>`)
								})
								docs_tabs.push('</div></div>')
								if (html) {
									let text = `---\ntitle: ${title}\nright_none: true\n---\n` + docs_tabs.join('') + html
									fs.writeFile(`${folderNameNew}/README.md`, text, function (err) {
										if (err) return console.log(err);
										console.log("The file was saved!");
										_this.extractFiles_second(folderTarget, format)
									});
								}
							}
						}
						if (isDir) {
							_this.mkDir(folderNameNew + "/" + filename).then(() => {//先创建目录
								ergodicDir(filedir, folderNameNew + "/" + filename, format);
							})
						}//递归，如果是文件夹，就继续遍历该文件夹下面的文件
					})
				});
			});
		}
		_this.deleteall(folderNew)
		_this.mkDir(folderNew).then(() => {//先创建目录
			let Path = path.resolve(`./${folderTarget}`);//获取绝对路径
			ergodicDir(Path, folderNew, format);
		})
	},
	extractFiles_second(folderTarget, format) {
		let path = require('path');//path模块
		let folderNew = `${folderTarget}_${format}`;
		let _this = module.exports;

		const ergodicDir = (Path, folderNameNew, format) => {
			fs.readdir(Path, (err, files) => {
				err && console.warn('路径读取出错', err);
				//遍历读取到的文件列表
				files.forEach((filename, i) => {
					let filedir = path.join(Path, filename);//完整的路径
					//根据文件路径获取文件信息，返回一个fs.Stats对象
					fs.stat(filedir, (error, stats) => {
						error && console.warn('获取文件stats失败', error);
						let isFile = stats.isFile(); //是文件
						let isDir = stats.isDirectory(); //是文件夹
						if (isFile) {
							let content = fs.readFileSync(filedir, 'utf-8');
							let $ = cheerio.load(content);
							let html = $('.contents').html()
							if (html) {
								let tabdata = []
								for (let i = 0; i < _this.tabsdata.length; i++) {
									const element = _this.tabsdata[i];
									tabdata.push(element.href)
								}
								if (tabdata.includes(filename)) {
									console.log(filename)
									let docs_tabs = [
										'<div class="docs-tabs">',
										'<div class="btn-group" role="group" aria-label="...">',
										'<a href="index.html" type="button" class="btn btn-default">概览</a>'
									]
									for (let j = 0; j < _this.tabsdata.length; j++) {
										let href = _this.tabsdata[j].href
										let text = _this.tabsdata[j].text
										if (href == filename) docs_tabs.push(`<a href="${href}" type="button" class="btn btn-default active">${text}</a>`)
										else docs_tabs.push(`<a href="${href}" type="button" class="btn btn-default">${text}</a>`)
									}
									docs_tabs.push('</div></div>')
									let text = `---\nright_none: true\n---\n` + docs_tabs.join('') + html
									fs.writeFile(`${folderNameNew}/${_this.getFileName(filename)}.md`, text, function (err) {
										if (err) return console.log(err);
										console.log("The file was saved!");
										_this.readDirSync(folderNew)
									});
								}
							}
						}

						isDir && ergodicDir(filedir, folderNameNew, format); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
					})
				});
			});
		}
		// _this.mkDir(folderNew).then(() => {//先创建目录
		let Path = path.resolve(`./${folderTarget}`);//获取绝对路径
		ergodicDir(Path, folderNew, format);
		// })
	},
	// 在所有指定目录最后面加点东西
	extractFiles_add(folderTarget, format, html_content) {
		let path = require('path');//path模块
		let folderNew = `${folderTarget}_${format}`;
		let _this = module.exports;
		const ergodicDir = (Path, folderNameNew, format) => {
			fs.readdir(Path, (err, files) => {
				err && console.warn('路径读取出错', err);
				//遍历读取到的文件列表
				files.forEach((filename) => {
					let filedir = path.join(Path, filename);//完整的路径
					//根据文件路径获取文件信息，返回一个fs.Stats对象
					fs.stat(filedir, (error, stats) => {
						error && console.warn('获取文件stats失败', error);
						let isFile = stats.isFile(); //是文件
						let isDir = stats.isDirectory(); //是文件夹
						if (isFile) {
							var content = fs.readFileSync(filedir, 'utf-8');
							let text = content + "\n" + html_content
							fs.writeFile(`${folderNameNew}/${_this.getFileName(filename)}.md`, text, function (err) {
								if (err) return console.log(err);
								console.log("The file was saved!");
								_this.extractFiles_second(folderTarget, format)
							});
						}
						if (isDir) {
							_this.mkDir(folderNameNew + "/" + filename).then(() => {//先创建目录
								ergodicDir(filedir, folderNameNew + "/" + filename, format);
							})
						}//递归，如果是文件夹，就继续遍历该文件夹下面的文件
					})
				});
			});
		}
		_this.deleteall(folderNew)
		_this.mkDir(folderNew).then(() => {//先创建目录
			let Path = path.resolve(`./${folderTarget}`);//获取绝对路径
			ergodicDir(Path, folderNew, format);
		})
	},
}
